package com.imooc.web.service.impl;

import com.imooc.web.lock.DistributedLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imooc.item.service.ItemsService;
import com.imooc.order.service.OrdersService;
import com.imooc.web.service.CulsterService;

@Service("buyService")
public class CulsterServiceImpl implements CulsterService {
	
	final static Logger log = LoggerFactory.getLogger(CulsterServiceImpl.class);
	
	@Autowired
	private ItemsService itemService;

	@Autowired
	private OrdersService ordersService;

	@Autowired
	private DistributedLock distributedLock;
	
	@Override
	public void doBuyItem(String itemId) {
		// 减少库存
		itemService.displayReduceCounts(itemId, 1);
		
		// 创建订单
		ordersService.createOrder(itemId);
	}
	
	@Override
	public boolean displayBuy(String itemId) {

		//获取锁
		distributedLock.getLock();

		int buyCounts = 5;
		try {
			// 1. 判断库
			int stockCounts = itemService.getItemCounts(itemId);
			if (stockCounts < buyCounts) {
				log.info("库存剩余{}件，用户需求量{}件，库存不足，订单创建失败...",
						stockCounts, buyCounts);
				distributedLock.releaseLock();//处理完之前要释放锁
				return false;
			}
			// 模拟业务处理，方便复现高并发情况数据不一致的问题
//			将商品数量设置为6，5s内在浏览器输入buy、buy2，控制台会看到两个"订单创建成功..."，数据库发现商品数为-4
//			http://localhost:8080/buy2?itemId=2
//			http://localhost:8080/buy?itemId=2
			Thread.sleep(5000);
		} catch (Exception e) {
			distributedLock.releaseLock();//处理完之前要释放锁
			e.printStackTrace();
		}

		// 2. 创建订单
		boolean isOrderCreated = ordersService.createOrder(itemId);
		
		// 3. 创建订单成功后，扣除库存
		if (isOrderCreated) {
			log.info("订单创建成功...");
			itemService.displayReduceCounts(itemId, buyCounts);
		} else {
			log.info("订单创建失败...");
			distributedLock.releaseLock();//处理完之前要释放锁
			return false;
		}
		distributedLock.releaseLock();//处理完之前要释放锁
		return true;
	}
	
}

